package com.demo.core.orm.ibatis.sqlmap.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.ibatis.sqlmap.engine.type.BaseTypeHandler;


/**
 * M-D：JDBC类型转换
 * DB:'t'=Modal:'true';'f'=Modal:'false'
 * 其他规则与BooleanTypeHandler相同
 * @see BooleanTypeHandler
 * @author ryuu-kk
 *
 */
public class BooleanTypeHandler extends BaseTypeHandler {
	
	@Override
	public Object getResult(ResultSet rs, String columnName) throws SQLException {
		Object value = rs.getObject(columnName);
		if (value == null) {
			return new Boolean(false);
		}
		if (value instanceof String) {
			if (((String) value).toLowerCase().startsWith("t")) {
				return new Boolean(true);
			} else if (((String) value).toLowerCase().startsWith("f")) {
				return new Boolean(false);
			}
		}
		//其他类型参照result.getBooean()函数说明
		boolean b = rs.getBoolean(columnName);
	    if (rs.wasNull()) {
	      return null;
	    } else {
	      return new Boolean(b);
	    }
	}

	@Override
	public Object getResult(ResultSet rs, int columnIndex) throws SQLException {
		Object value = rs.getObject(columnIndex);
		if (value == null) {
			return new Boolean(false);
		}
		if (value instanceof String) {
			if (((String) value).toLowerCase().startsWith("t")) {
				return new Boolean(true);
			} else if (((String) value).toLowerCase().startsWith("f")) {
				return new Boolean(false);
			}
		}
		//其他类型参照result.getBooean()函数说明
		boolean b = rs.getBoolean(columnIndex);
	    if (rs.wasNull()) {
	      return null;
	    } else {
	      return new Boolean(b);
	    }
	}

	@Override
	public Object getResult(CallableStatement cs, int columnIndex) throws SQLException {
		Object value = cs.getObject(columnIndex);
		if (value == null) {
			return new Boolean(false);
		}
		if (value instanceof String) {
			if (((String) value).toLowerCase().startsWith("t")) {
				return new Boolean(true);
			} else if (((String) value).toLowerCase().startsWith("f")) {
				return new Boolean(false);
			}
		}
	    boolean b = cs.getBoolean(columnIndex);
	    if (cs.wasNull()) {
	      return null;
	    } else {
	      return new Boolean(b);
	    }
	}

	@Override
	public void setParameter(PreparedStatement ps, int i, Object parameter,	String jdbcType) throws SQLException {
		
		if (parameter == null) {
			ps.setString(i, "F");
		} else if (parameter instanceof Boolean) {
			if ((Boolean) parameter) {
				ps.setString(i, "T");
			} else {
				ps.setString(i, "F");
			}
		} else {
			ps.setBoolean(i, ((Boolean) parameter).booleanValue());
		}
	}

	@Override
	public Object valueOf(String s) {
		if (s == null) {
			return Boolean.FALSE;
		}
		if (s.toLowerCase().startsWith("t")) {
			return new Boolean(true);
		} else if (s.toLowerCase().startsWith("f")) {
			return new Boolean(false);
		}
		return Boolean.valueOf(s);
	}
}